package com.sen.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sen.reggie.common.CustomException;
import com.sen.reggie.dto.DishDto;
import com.sen.reggie.dto.SetmealDto;
import com.sen.reggie.entity.Dish;
import com.sen.reggie.entity.DishFlavor;
import com.sen.reggie.entity.Setmeal;
import com.sen.reggie.entity.SetmealDish;
import com.sen.reggie.mapper.SetmealMapper;
import com.sen.reggie.service.SetmealDishService;
import com.sen.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Zs
 * @date:2022/6/2 18:35
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
      @Autowired
    private SetmealDishService setmealDishService;
      @Autowired
    private  SetmealService setmealService;

    /**
     * 新增商品套餐，同时需要保存套餐与菜品的关联关系
     * @param SetmealDto
     */
    @Transactional
    public  void saveWithDish(SetmealDto SetmealDto){
           //保存套餐的基本信息，操作setmeal执行insert操作
             this.save(SetmealDto);
        List<SetmealDish> setmealDishes=SetmealDto.getSetmealDishes();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(SetmealDto.getId());
            return  item;
        }).collect(Collectors.toList());

           //保存套餐与菜品的关联信息
         setmealDishService.saveBatch(setmealDishes);
    }


    /**
     * 根据套餐商品ID删除套餐与套餐相关的关系
     *
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
         //停售状态的套餐商品才能删除
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        long count = this.count(queryWrapper);
        //如果还在起售抛出业务异常
        if(count>0){

           throw   new CustomException("套餐正在起售,无法删除");
        }
        //正常删除
        this.removeByIds(ids);
        //删除关联表的套餐信息
        LambdaQueryWrapper<SetmealDish> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapper1);

    }



}
